package com.ja.openchat.ui.contact;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProviders;

import com.google.gson.JsonObject;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityEditUserProfileBinding;
import com.ja.openchat.ui.MainActivity;
import com.ja.openchat.viewmodels.EditUserProfileViewModel;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.config.AppConfigInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.OrgUserInfo;
import com.zy.openchat.core.model.user.UserFullInfo;
import com.zy.openchat.core.model.user.UserInfo;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;

import me.goldze.mvvmhabit.base.BaseActivity;

public class EditUserProfileActivity extends BaseActivity<ActivityEditUserProfileBinding,EditUserProfileViewModel> implements View.OnClickListener {

    public static void start(Activity activity, UserInfo user, ChatInfo chat, boolean blockContact) {
        Intent intent = new Intent();
        intent.setClass(activity, EditUserProfileActivity.class);
        intent.putExtra("chat", chat);
        intent.putExtra("user", user);
        intent.putExtra("blockContact", blockContact);
        activity.startActivity(intent);
    }
    public UserInfo user;
    private ChatInfo chatInfo;
    private UserFullInfo userFullInfo;
    private boolean blockContact = false;
    private boolean isCompleteSave = false;
    private boolean isCompleteSet = false;


    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_edit_user_profile;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public EditUserProfileViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(EditUserProfileViewModel.class);
    }


    @Override
    public void initView() {
        super.initView();
        if (getIntent() != null) {
            user = getIntent().getParcelableExtra("user");
            chatInfo = getIntent().getParcelableExtra("chat");
            blockContact = getIntent().getBooleanExtra("blockContact", false);
        }
        if(chatInfo==null){
            chatInfo = new ChatInfo();
        }
        binding.deleteLayout.setOnClickListener(this);
        binding.addLayout.setOnClickListener(this);

        binding.headerImageView.setTextSize(27);
        binding.toolbar.tvBarTitle.setText(getString(R.string.edit_text));
        binding.toolbar.tvOkRight.setVisibility(View.VISIBLE);
        binding.toolbar.tvOkRight.setBackground(ContextCompat.getDrawable(this,R.drawable.transparent_shape));
        binding.toolbar.tvOkRight.setTextColor(ContextCompat.getColor(this,R.color.nav_btn_bg));
        binding.toolbar.tvOkRight.setText(getString(R.string.finish_text));
        binding.toolbar.tvOkRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isCompleteSave = false;
                isCompleteSet = false;
                if(user!=null&&!user.is_contact){
                    isCompleteSave = true;
                }else{
                    saveUserNickname(binding.etRemark.getText().toString());
                }
//                blockSwitchClick();
            }
        });
        binding.toolbar.ivBarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        viewModel.setContext(this);
        syncUserFullInfo();
        requestOrgUserInfo();
    }


    public void resetUI() {
        if (userFullInfo != null) {
            binding.blockedSwitch.setText(userFullInfo.is_blocked ? getString(R.string.remove_blacklist) : getString(R.string.join_black_list));
        }
        binding.blockedSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                blockSwitchClick();
            }
        });
        if (user != null) {
            binding.headerImageView.showUser(user);
            binding.remarkLayout.setVisibility(user.is_contact ? View.VISIBLE : View.GONE);
            if (blockContact) {
                binding.deleteLayout.setVisibility(View.GONE);
                binding.addLayout.setVisibility(View.GONE);
            } else {
                binding.deleteLayout.setVisibility(View.VISIBLE);
                binding.addLayout.setVisibility(View.VISIBLE);
                if (user.is_contact) {
                    binding.addLayout.setVisibility(View.GONE);
                } else {
                    if (!canAddFriend()) {
                        binding.addLayout.setVisibility(View.GONE);
                    }
                    binding.deleteLayout.setVisibility(View.GONE);
                }
            }
            if (user.is_contact) {
                if (orgUserInfo != null) {
                    if (!orgUserInfo.displayName().equals(user.displayName())) {
                        binding.etRemark.setText(user.displayName());
                    } else {
                        binding.etRemark.setText("");
                    }
                } else {
                    binding.etRemark.setText("");
                }
            } else {
                binding.etRemark.setText("");
            }
        }
    }

    private boolean canAddFriend() {
        AppConfigInfo info = AppConfigInfo.getAppConfigInfo();
        if (info != null) {
            if (info.onlyWhiteAddFriend) {
                return orgUserInfo != null ? orgUserInfo.isInternal : false;
            }
        }
        return true;
    }


    private void saveUserNickname(String name) {
        long toBeModifyUserId;
        if(user==null){
            toBeModifyUserId = chatInfo.userId();
        }else{
            toBeModifyUserId = user.id;
        }
        if (StringUtils.isEmpty(name)) {
            name = "";
        }
        showProgress();
        TelegramManager.getTelegramManager().setContactNickName(this, toBeModifyUserId, name, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (obj.ok) {//设置成功
                    finish();
                } else {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }


    private void blockSwitchClick() {
        if (userFullInfo == null) {
            resetUI();
            syncUserFullInfo();
            return;
        }
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(R.string.dialog_title_tip).setMessage(userFullInfo.is_blocked ? getString(R.string.remove_black_list_question) : getString(R.string.join_black_list_question));
        dialog.setPositiveButton(R.string.dialog_ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        blockUser();
                    }
                });
        dialog.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                resetUI();
            }
        });
        dialog.show();
    }

    private void blockUser() {
        showProgress();
        TelegramManager.getTelegramManager().blockUser(this, chatInfo.id, !userFullInfo.is_blocked, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                    resetUI();
                } else {
                    userFullInfo.is_blocked = !userFullInfo.is_blocked;
                    isCompleteSet = true;
                    resetUI();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));

            }
        });
    }

    private void syncUserFullInfo() {
        TelegramManager.getTelegramManager().requestContactFullInfo(this, chatInfo.id, new TgResultBlock<UserFullInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, UserFullInfo obj) {
                if (obj != null) {
                    userFullInfo = obj;
                    resetUI();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }

    private OrgUserInfo orgUserInfo;
    public void requestOrgUserInfo() {
        if (user != null) {
            TelegramManager.getTelegramManager().requestOrgContactInfo(this, user.id, new TgResultBlock<OrgUserInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, OrgUserInfo obj) {
                    if (obj != null) {
                        orgUserInfo = obj;
                        resetUI();
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                }
            });
        }
    }
   public void onClick(View view) {
        switch (view.getId()) {
            case R.id.addLayout://添加好友
                if (user != null) {
                    clickAdd();
                }
                break;
            case R.id.deleteLayout://删除好友
                if (user != null) {
                    clickDelete();
                }
                break;
        }
    }

    private void clickAdd() {//添加好友
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(R.string.dialog_title_tip).setMessage(String.format(getString(R.string.want_add_somebody_as_friend), user.displayName()));
        dialog.setPositiveButton(R.string.dialog_ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        doAddContact();
                    }
                });
        dialog.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void doAddContact() {
        showProgress();
        TelegramManager.getTelegramManager().addContact(this, user, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                } else {
                    showErrorTip(String.format(getString(R.string.somebody_added_friends), user.displayName()));
                    TelegramManager.getTelegramManager().sendBeFriendMessage(EditUserProfileActivity.this, user.id, new TgResultBlock<TgResponse>() {
                        @Override
                        public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                        }

                        @Override
                        public void onTimeout(Map<String, Object> request) {
                        }
                    });
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private void clickDelete() {//删除好友
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(R.string.dialog_title_tip).setMessage(String.format(getString(R.string.want_delete_friend), user.displayName()));
        dialog.setPositiveButton(R.string.dialog_ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        doDeleteContact();
                    }
                });
        dialog.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void doDeleteContact() {
        showProgress();
        TelegramManager.getTelegramManager().deleteContact(this, user.id, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                } else {
                    showErrorTip(String.format(getString(R.string.removed_friends_list), user.displayName()));
                    startActivity(new Intent(EditUserProfileActivity.this, MainActivity.class));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }
}
